import 'dart:async';

import 'package:get/get.dart';
import 'package:ball_lion/base/base_controller.dart';
import 'package:ball_lion/entity/home/news_comment_entity.dart';
import 'package:ball_lion/server/api/home_api.dart';

class CommentViewLogic extends BaseController {
  int id = Get.arguments;
  List<NewsCommentEntity>? comments;
  int page = 1;
  int pageSize = 20;
  Map<int, bool> existMap = {};
  bool hasMoreComment = true;
  // int commentSort = 1;
  int commentsCount = 0;
  int commentSort = 1;

  @override
  void onInit() {
    // TODO: implement onInit
    super.onInit();
    fetchComments();
  }

  fetchComments({bool loadNew = false}) async {
    try {
      // final p = page;
      if (loadNew) {
        page = 1;
      }
      final r = await HomeApi.commentList(id,
          type: commentSort, page: page, size: pageSize);
      List rows = r.data['d']['rows'];
      commentsCount = r.data['d']['total'];
      final l = rows
          .map<NewsCommentEntity>((e) => NewsCommentEntity.fromJson(e))
          .toList();
      // if (p != page) {
      //   return;
      // }
      if (page == 1) {
        comments = [];
        existMap = {};
      }
      page += 1;
      hasMoreComment = (l.length == 20);
      l.removeWhere((element) {
        if (existMap[element.id ?? 0] ?? false) {
          return true;
        }
        existMap[element.id ?? 0] = true;
        return false;
      });
      comments!.addAll(l);
      update();
    } catch (err) {}
  }

  FutureOr<bool> doSndComment(String comment) async {
    final r = await HomeApi.add(id, comment);
    if (r.data['c'] == 200) {
      final c = NewsCommentEntity.fromJson(r.data['d']);
      comments!.insert(0, c);
      update();
      return true;
    }
    return false;
  }

  @override
  void loadMore() async {
    if (hasMoreComment) await fetchComments();
  }
}
